import cgi

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson
from google.appengine.ext import db


def init():
  counter = SimpleCounter(counter = 68 * 10000 * 10000)
  db.put(counter)

def decrement(sc):
  sc.counter = sc.counter - 1
  db.put(sc)

class SimpleCounter(db.Model):
  counter = db.IntegerProperty()

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('welcome to hellcounter API!')

class Decrement(webapp.RequestHandler):
  def get(self):
    sclist = db.GqlQuery("SELECT * FROM SimpleCounter LIMIT 1")
    for sc in sclist:
      db.run_in_transaction(decrement,sc)
    data = {
      "response" : "OK",
      "content" : {
      },
    }
    self.response.headers['Content-Type'] = 'application/json'
    #self.response.headers['Content-Type'] = 'text/plain'
    simplejson.dump(data, self.response.out, ensure_ascii=False)

class GetCounter(webapp.RequestHandler):
  def get(self):
    sclist = db.GqlQuery("SELECT * FROM SimpleCounter LIMIT 1")
    counter = -1
    for sc in sclist:
      counter = sc.counter
    data = {
      "response" : "OK",
      "content" : {
         "counter" : counter
      },
    }
    self.response.headers['Content-Type'] = 'application/json'
    #self.response.headers['Content-Type'] = 'text/plain'
    simplejson.dump(data, self.response.out, ensure_ascii=False)

application = webapp.WSGIApplication(
  [
    ('/', MainPage),
    ('/decrement', Decrement),
    ('/getcounter', GetCounter),
  ],
  debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
